package fun.lifepoem.blog.utils.localfile;

import fun.lifepoem.blog.domain.note.AnalysisArticleTag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Yiwyn
 * @create 2022/9/17 23:04
 */
@Component
@Slf4j
public class LocalFileUtils {


    @Value("${git.repository-path}")
    private String repositoryPath;


    /**
     * 文件夹处理
     */
    public File getRootFile() {
        File file = new File(repositoryPath);

        File[] files = file.listFiles();

        if (ObjectUtils.isEmpty(files)) {
            log.info("本地文件列表为空");
            return null;
        }

        return file;
    }

    public List<File> getRootDir() {
        File file = new File(repositoryPath);

        File[] files = file.listFiles();

        if (ObjectUtils.isEmpty(files)) {
            log.info("本地文件列表为空");
            return null;
        }
        List<File> fileList = Arrays.stream(files)
                .filter(p -> p.isDirectory() && !p.getName().contains("."))
                .collect(Collectors.toList());


        return fileList;
    }

    /**
     * 将拆分出path中的路径和文件
     *
     * @param path 需要进行拆分的路径
     */
    public AnalysisArticleTag getArticlesTagFromCommmitPath(String path) {
        String url = repositoryPath + path;
        log.info("拆分url:{}", url);
        File file = new File(url);
        AnalysisArticleTag result = new AnalysisArticleTag();
        if (file.isFile()) {
            result.setFile(file);
        }
        String[] splitPaths = path.split("/");
        List<String> tags = new ArrayList<>(Arrays.asList(splitPaths).subList(0, splitPaths.length - 1));
        result.setTags(tags);
        return result;
    }


    /**
     * 读取文件内容为字符串，同时保留换行，空行等
     *
     * @param noteFile
     * @return
     * @throws IOException
     */
    public String getContentFromFile(File noteFile) throws IOException {
        FileInputStream fis = null;

        StringBuilder content = new StringBuilder();
        byte[] bytes = new byte[1024];


        fis = new FileInputStream(noteFile);
        int len;
        while ((len = fis.read(bytes)) != -1) {
            content.append(new String(bytes, 0, len));
        }

        fis.close();
        return content.toString();
    }

    public String getRelativePath(String absolutePath) {
        String absoluteStr = absolutePath.replace("\\", "/");
        String relativePath = absoluteStr;
        if (absoluteStr.contains(repositoryPath.replace("\\", "/"))) {
            relativePath = absoluteStr.substring(repositoryPath.length());
        }
        return relativePath;
    }


}
